//
//  RaeRequestParameterConfig.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import Foundation
import CoreTelephony
import CommonCrypto
import Alamofire

class RaeRequestParameterConfig: NSObject {
    
    static let shared = RaeRequestParameterConfig()
    
    /// 服务器地址,必须传
    public var baseUrlString = "https://www.lwan.com/api/app/v3/?"
    public var baseUrlV5String = "https://www.lwan.com/api/app/v5/?"
    public var baseUrlStr = "https://www.lwan.com/?"
    public var host = "www.lwan.com"
//    public var baseUrlString = "http://beta.www.77.top/api/app/v3/?"
//    public var baseUrlV5String = "http://beta.www.77.top/api/app/v5/?"
//    public var baseUrlStr = "http://beta.www.77.top/?"
//    public var host = "beta.www.77.top"
    /// 请求token,必须传
    public var requestToken: String = ""
    var tStr = ""
    
    public func getURLStr()-> String{
        return self.baseUrlString + "api/app/v3/?"
    }
    
    public func getURLUpLoadStr()-> String{
        return self.baseUrlString + "?"
    }
    
    public func getTStr()-> String{
        tStr = "\(Date().toTimeStamp())\(getRandomNumber(from: 101, to: 998))"
        return tStr
    }
    
    public func encrySign() -> String {
        
        guard let uids = UserDefaultsManager.getString(forKey: .uid), uids.count > 0  else { return "" }
        let sign = "\(uids)\(tStr)\("fsd213ewdsadqwe2121213edsad")"
        let signMD5 = md5HexDigest(sign)
        return signMD5
    }
    
    func getRandomNumber(from: Int, to: Int) -> Int {
        return Int.random(in: from...to)
    }
    
    func md5HexDigest(_ input: String) -> String {
        let data = Data(input.utf8)
        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        
        data.withUnsafeBytes {
            _ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest)
        }
        
        return digest.map { String(format: "%02x", $0) }.joined()
    }
}


extension RaeRequestParameterConfig {
    
    /// 发布动态
    /// - Parameters:
    ///   - type: <#type description#>
    ///   - id: <#id description#>
    ///   - success: <#success description#>
    ///   - failure: <#failure description#>
    func pushDynamic(param: [String: String],success:@escaping ((_:String) -> Void), failure: @escaping((_: String) -> Void)) {

        var para = param
        var uid = ""
        if let user_id = UserDefaultsManager.getString(forKey: .uid) {
            uid = user_id
        }
        let tStr = RaeRequestParameterConfig.shared.getTStr()
        let sign = RaeRequestParameterConfig.shared.encrySign()
        para["uid"] = uid
        para["t"] = tStr
        para["sign"] = sign
        
        let url = baseUrlString + RaeRequestApi.pushDynamic.path
        AF.request(URL(string: url)!, method: .get, parameters: para).responseString { (responses) in
            
            if responses.value != nil {
                let result:String = responses.value ?? ""
                if result != "﻿" {
                    
                    success("success")
                }else {
                    print("没有获取到数据")
                    //                    self.p -= 1
                }
                
            }else {
                print("获取数据失败")
                //                self.p -= 1
                
            }
        }
    }
    /// 上传图片
    /// - Parameters:
    ///   - uploadImage: 图片
    ///   - success: 成功
    ///   - failure: 失败
    func uploadImage(uploadImage:UIImage,success:@escaping ((_ urlString:String) -> Void), failure: @escaping((_ errorMessage: String) -> Void)) {

        var uid = ""
        if let user_id = UserDefaultsManager.getString(forKey: .uid) {
            uid = user_id
        }
        let tStr = RaeRequestParameterConfig.shared.getTStr()
        let sign = RaeRequestParameterConfig.shared.encrySign()
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data",
            "Host": RaeRequestParameterConfig.shared.host,
            "Transfer-Encoding": "chunked",
        ]

        let url = baseUrlStr + RaeRequestApi.upload.path
        AF.upload(multipartFormData: { multipartFormData in
            let data = uploadImage.jpegData(compressionQuality: 0.5)
            multipartFormData.append(Data(data!), withName: "image", fileName: "123.png", mimeType: "image/png")
            multipartFormData.append(Data(uid.utf8), withName: "uid")
            multipartFormData.append(Data(tStr.utf8), withName: "t")
            multipartFormData.append(Data(sign.utf8), withName: "sign")
        }, to: url, headers: headers)
            .responseJSON { response in
                debugPrint(response)
                if response.data != nil {
                    let result = self.DataToJSONString(data: response.data ?? Data())
                    success(result ?? "")
                    
                }else {
                    print("获取数据失败")
                    
                }
            }
    }
    /// 上传视频
    /// - Parameters:
    ///   - uploadImage: 视频
    ///   - success: 成功
    ///   - failure: 失败
    func uploadVideo(record:Data,suffix:String,success:@escaping ((_ urlString:String) -> Void), failure: @escaping((_ errorMessage: String) -> Void),progress: @escaping((_: String) -> Void)) {
        
        var uid = ""
        if let user_id = UserDefaultsManager.getString(forKey: .uid) {
            uid = user_id
        }
        let tStr = RaeRequestParameterConfig.shared.getTStr()
        let sign = RaeRequestParameterConfig.shared.encrySign()
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data",
            "Host": RaeRequestParameterConfig.shared.host,
            "Transfer-Encoding": "chunked",
        ]
        let url = baseUrlStr + RaeRequestApi.upload.path
        
        AF.upload(multipartFormData: { multipartFormData in
            //            let data = uploadImage.jpegData(compressionQuality: 0.5)
            multipartFormData.append(record, withName: "image", fileName: "123.mp4", mimeType: "audio/wav")
            multipartFormData.append(Data(uid.utf8), withName: "uid")
            multipartFormData.append(Data(tStr.utf8), withName: "t")
            multipartFormData.append(Data(sign.utf8), withName: "sign")
        }, to: url, headers: headers, requestModifier: nil)//{$0.timeoutInterval = 300}
            .responseJSON { response in
                debugPrint(response)
                if response.data != nil {
                    let result = self.DataToJSONString(data: response.data ?? Data())
                    success(result ?? "")
                }else {
                    print("获取数据失败")
                    failure("上传失败，请重试~")
                    
                }
            }
            .uploadProgress { pros in
                print(pros.fractionCompleted)
                let str = String(format: "%.f", pros.fractionCompleted * 100)
                progress(str)
            }
    }
    
    func DataToJSONString(data: Data) -> String? {
        
        let JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        return JSONString
    }
    
    func JSONStringToDictionary(jsonString:String) ->NSDictionary{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
}


extension UIDevice {
    
    static var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        if identifier.contains("iPad") {
            return "iPad, 测试人员或者审核人员"
        }
        switch identifier {
        case "iPhone7,1": return "iPhone 6 Plus"
        case "iPhone7,2": return "iPhone 6"
        case "iPhone8,1": return "iPhone 6s"
        case "iPhone8,2": return "iPhone 6s Plus"
        case "iPhone8,4": return "iPhone SE"
        case "iPhone9,1": return "iPhone 7"
        case "iPhone9,2": return "iPhone 7 Plus"
        case "iPhone9,3": return "iPhone 7"
        case "iPhone9,4": return "iPhone 7 Plus"
        case "iPhone10,1": return "iPhone 8"
        case "iPhone10,2": return "iPhone 8 Plus"
        case "iPhone10,3": return "iPhone X"
        case "iPhone10,4": return "iPhone 8"
        case "iPhone10,5": return "iPhone 8 Plus"
        case "iPhone10,6": return "iPhone X"
        case "iPhone11,8": return "iPhone XR"
        case "iPhone11,2": return "iPhone XS"
        case "iPhone11,4": return "iPhone XS Max"
        case "iPhone11,6": return "iPhone XS Max"
        case "iPhone12,1": return "iPhone 11"
        case "iPhone12,3": return "iPhone 11 Pro"
        case "iPhone12,5": return "iPhone 11 Pro Max"
        case "iPhone13,1": return "iPhone 12 mini"
        case "iPhone13,2": return "iPhone 12"
        case "iPhone13,3": return "iPhone 12 Pro"
        case "iPhone13,4": return "iPhone 12 Pro Max"
        case "iPhone14,2": return "iPhone 13 Pro"
        case "iPhone14,3": return "iPhone 13 Pro Max"
        case "iPhone14,4": return "iPhone 13 Mini"
        case "iPhone14,5": return "iPhone 13"
        
        case "iPad13,9": return "iPad Pro 12.9 inch 5th Gen"
        case "iPad13,10": return "iPad Pro 12.9 inch 5th Gen"
        case "iPad13,11": return "iPad Pro 12.9 inch 5th Gen"
        case "iPad14,1": return "iPad mini (6th generation) Wi-Fi"
        case "iPad14,2": return "iPad mini (6th generation) Wi-Fi + Cellular"
        
        case "i386": return "Simulator"
        case "x86_64": return "Simulator"
        default: return ""
        }
    }
}
